var mongoose = require('mongoose');
var models = require('../models');
var Tab = models.Tab;
var Topic = models.Topic;
var User = models.User;
var Reply = models.Reply;
var services = require('../services');
var topicServ = services.topic;
var EventProxy = require('eventproxy');
var moment = require('moment');
var config = require('../config');
var _ = require('lodash');

exports.index = function (req, res, next) {
	var tabId = req.params.tabId || 'all',
		page = parseInt(req.params.page) || 1,
		query = {},
		options = {
			skip: config.topicPageLimit * (page - 1),
			limit: config.topicPageLimit,
			sort: '-createAt'
		};
	if (tabId != 'all')
		query.tabId = tabId;
	var ep = new EventProxy();
	ep.fail(next);
	ep.all('topics', 'pageTotal', function (topics, pageTotal) {
		res.locals.tabs = config.tabs || [];
		res.locals.tabId = tabId;
		res.render('index', { topics: topics, pageTotal: pageTotal, page: page });
	});
	//获取主题列表
	topicServ.queryList(query, options,ep.done('topics'));
	
	//获取页数
	topicServ.queryPage(query,ep.done('pageTotal'));
}

exports.importDb = function (req, res) {
	var authorId = '56517b41e812f564076eb573';
	var data = [];
	data.push({
		tabName: '问答',
		topics: [
			{ title: 'nodeJs该怎么学？', content: 'RT' },
			{ title: 'express是什么？', content: 'RT' },
			{ title: '求助nodejs运行出错！！！', content: 'RT' },
			{ title: 'node.js前景如何？优势有哪些？', content: 'RT' }
		]
	});
	data.push({
		tabName: '分享',
		topics: [
			{ title: 'node.js入门教程', content: 'RT' },
			{ title: 'express3.0到4.0移植教程', content: 'RT' }
		]
	});

	data.forEach(function (item) {
		var tab = new Tab();
		tab.name = item.tabName;
		tab.save(function (err) {
			if (err) {
				console.log(err.message);
				return;
			}
			item.topics.forEach(function (t) {
				var topic = new Topic();
				topic.tabId = tab._id;
				topic.title = t.title;
				topic.content = t.content;
				topic.authorId = authorId;
				topic.save(function (err) { if (err) console.log(err); });
			})
		});
	});

	res.redirect('/');
}